﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebApiSecurity.Api
{
    public static class Step03
    {
        public static void Register(HttpConfiguration config)
        {
            config.MessageHandlers.Add(new AuthenticationHandler());

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
        }

        private class AuthenticationHandler : DelegatingHandler
        {
            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var accessKey = request.Headers.Where(x => x.Key == "Demo-Key").SelectMany(x => x.Value).FirstOrDefault();

                if (string.IsNullOrWhiteSpace(accessKey) || !Repository.Keys.Contains(accessKey))
                    return new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid App Access Key")).Response;

                return await base.SendAsync(request, cancellationToken);
            }
        }

        private static class Repository
        {
            public static readonly IList<string> Keys = new List<string> {"920ab4e7-27cf-4236-99b2-7538ce11c28e"};
        }
    }
}
